package com.yyh.synctool.server.service.impl;

import com.yyh.common.StringCommon;
import com.yyh.synctool.server.mapper.AuthMapper;
import com.yyh.synctool.server.pojo.entity.LoginEntity;
import com.yyh.synctool.server.service.AuthService;
import com.yyh.synctool.server.util.MD5Utils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @author xuan
 * @create 2021/12/18
 */
@Slf4j
@Service
public class AuthServiceImpl implements AuthService
{
    private AuthMapper authMapper;

    @Autowired
    public AuthServiceImpl(AuthMapper authMapper) {
        this.authMapper = authMapper;
    }

    @Override
    public boolean authorize(String gsid, String credential) {
        if (StringCommon.isEmpty(gsid) || StringCommon.isEmpty(credential)) {
            log.debug("待校验的参数不合法");
        }
        LoginEntity loginEntity = authMapper.findByGsid(gsid);
        if (null == loginEntity) {
            // 不存在
            log.debug("该公司id不存在：gsid={}", gsid);
            return false;
        }

        try {
            if (loginEntity.getPassword().equals(MD5Utils.getMd5Password(credential, loginEntity.getSalt()))) {
                log.debug("凭证校验成功：gsid={}", gsid);
                return true;
            } else {
                log.debug("凭证校验失败：gsid={}", gsid);
                return false;
            }

        } catch (Exception e) {
            // 防止未知异常
            log.error("凭证异常：gsid={}"+gsid);
            return false;
        }
    }
}
